package com.ease.integration.jms.util;

import java.util.Properties;

import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ease.common.exception.NestedException;
import com.ease.integration.jms.listener.MessageListenerCallback;

public class JmsMessageUtil {

	private static final Log log = LogFactory.getLog(JmsMessageUtil.class);

	public static void send(Properties environment, String connectionFactoryJndiName, String destinationJndiName, boolean transacted, int acknowledgementMode, String text) {
		InitialContext initialContext = null;
		QueueConnection queueConnection = null;
		try {
			initialContext = new InitialContext(environment);
			Object objRef = initialContext.lookup(connectionFactoryJndiName);
			queueConnection = ((QueueConnectionFactory) objRef).createQueueConnection();
			QueueSession queueSession = null;
			try {
				queueConnection.start();
				queueSession = queueConnection.createQueueSession(transacted, acknowledgementMode);

				TextMessage textMessage = queueSession.createTextMessage();
				textMessage.clearBody();
				textMessage.setText(text);
				Queue queue = (Queue) initialContext.lookup(destinationJndiName);

				QueueSender queueSender = null;

				try {
					queueSender = queueSession.createSender(queue);
					queueSender.send(textMessage);
					if (transacted) {
						queueSession.commit();
					}
				} finally {
					if (null != queueSender) {
						queueSender.close();
					}
				}
			} finally {
				if (null != queueSession) {
					queueSession.close();
				}
			}
		} catch (Exception e) {
			log.error("jms receive error occurs: ", e);
		} finally {
			try {
				if (null != queueConnection) {
					queueConnection.close();
				}
				if (null != initialContext) {
					initialContext.close();
				}
			} catch (Exception e) {
				log.error("jms receive error occurs: ", e);
			}
		}
	}

	public static void receive(Properties environment, String connectionFactoryJndiName, String destinationJndiName, boolean transacted, int acknowledgementMode, int latencySecond,
			MessageListenerCallback messageReceiverCallback) throws Exception {
		InitialContext initialContext = null;
		QueueConnection queueConnection = null;
		try {
			initialContext = new InitialContext(environment);

			Object objRef = initialContext.lookup(connectionFactoryJndiName);
			queueConnection = ((QueueConnectionFactory) objRef).createQueueConnection();
			QueueSession queueSession = null;
			try {
				queueConnection.start();
				queueSession = queueConnection.createQueueSession(transacted, acknowledgementMode);
				Queue queue = (Queue) initialContext.lookup(destinationJndiName);
				QueueReceiver queueReceiver = queueSession.createReceiver(queue);
				queueConnection.start(); // ɨ�����, ��ȡ��Ϣ

				// TextMessage textMessage = queueSession.createTextMessage();
				// textMessage.clearBody();
				// textMessage.setText(text);

				try {
					while (true) {
						Message message = queueReceiver.receive(1);

						if (null != messageReceiverCallback) {
							messageReceiverCallback.onMessage(message);
						}
						// System.out.println("��ʼ:"+txt.indexOf("<time>")+"
						// ����:"+txt.indexOf("</time>"));
						// System.out.println("ת����ʼʱ��:"+txt.substring(50,63));

						// long t1 = Long.parseLong(txt.substring(50,
						// 63));
						// System.out.println("ת��ʱ��:" +
						// (System.nanoTime() - t1));
						// cc = false;
						// �������� 2007.7.6

						//
						// ����Ϣ����д�뵽�ļ���
						// String msgId = message.getJMSMessageID();
						// msgId = msgId.replace(':', '_');
						// msgId = msgId.replace('<', '_');
						// msgId = msgId.replace('>', '_');
						// FileHelper.write2File(Constant.MSG_STORE_DIR+
						// msgId
						// +".txt",
						// message.getText());
						// long timeStamp = message.getJMSTimestamp();
						// Date d = new Date(timeStamp);
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm:s");
						// System.out.println(
						// "\n\n--------------------------------��ʼ����--------------------------------"
						// );
						// System.out.println("��ϢID:"+message.getJMSMessageID())
						// ;
						// System.out.println("����ʱ��:"+sdf.format(d));
						// System.out.println("��Ϣ����: " +
						// message.getText());
						// System.out.println(
						// "\n\n--------------------------------�������--------------------------------"
						// );
						// /System.out.println("����:" + (++i));

						// } else {
						// System.out.println("an unknow message type:");
						// System.out.println(message.getClass().getName());
						// break;
						// }
						// }

						try {
							Thread.sleep(latencySecond * 1000);
						} catch (InterruptedException e) {
						}

					}
				} finally {
					if (null != queueReceiver) {
						queueReceiver.close();
					}
				}
			} finally {
				if (null != queueSession) {
					queueSession.close();
				}
			}
		} catch (Exception e) {
			log.error("jms receive error occurs: ", e);
		} finally {
			try {
				if (null != queueConnection) {
					queueConnection.close();
				}
				if (null != initialContext) {
					initialContext.close();
				}
			} catch (Exception e) {
				log.error("jms receive error occurs: ", e);
			}
		}
	}

	/**
	 * ������SRM����PF,PF����CRM,3ϵͳ��������EJBʱ,<br>
	 * ����EJB�û���Ϣ(java.naming.security.principal,java.naming.security. credentials)���ݵ�����:<br>
	 * 2��ejb���õ�principal����ͬ<br>
	 * �����Լ�����,����spring��EJB����.
	 * 
	 * @return
	 */
	public static Object getSessionBeanHome(Properties environment, String jndiName, Class<?> ejbHome) throws Exception {
		try {
			javax.naming.InitialContext initialContext = new javax.naming.InitialContext(environment);
			try {
				Object objRef = initialContext.lookup(jndiName);
				if (java.rmi.Remote.class.isAssignableFrom(ejbHome))
					return javax.rmi.PortableRemoteObject.narrow(objRef, ejbHome);
				else
					return objRef;
			} catch (Exception e) {
				throw new NestedException("EJB invoker error\njndiName=" + jndiName + "\nejbHome=" + ejbHome, e);
			} finally {
				initialContext.close();
			}
		} catch (Exception e) {
			throw new NestedException("lookupHome error", e);
		}
	}
}
